﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Base.Extensions;
using Web.Base.Security;
using Web.Seller.Models;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;

namespace Web.Seller.Controllers
{
    public class OrderController : SellerBaseController
    {
        public OrderController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="size">分页大小</param>
        /// <param name="id">订单号</param>
        /// <param name="nick">商家昵称</param>
        /// <param name="title">商品标题</param>
        /// <param name="category">分类</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="commentStatus">评论状态</param>
        /// <param name="beginDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns></returns>
        public ActionResult Index(int page = 1, int size = 20, string id = null, string nick = null, string title = null,
                                      OrderCategory category = OrderCategory.Normal, OrderStatus? orderStatus = null, byte? commentStatus = null, DateTime? beginDate = null, DateTime? endDate = null)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Index();
            var orders = OrderService.GetPagedOrders(page, size, id, identity.Id, nick, true, title, category, orderStatus, commentStatus, beginDate, endDate).ToPagedList(page, size);
            if (orders.Count > 0)
            {
                var orderIds = orders.Select(o => o.Id).ToArray();
                var orderItems = OrderService.GetOrderItems(orderIds);
                foreach (var order in orders)
                {
                    order.OrderItems = orderItems.Where(o => o.OrderId == order.Id).ToList();
                }
            }
            model.Orders = orders;
            return View(model);
        }
        /// <summary>
        /// 订单详细信息
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Detail(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            var order = OrderService.GetOrder(param, identity.Id, true, true);
            model.Order = order;
            if (order.Status == OrderStatus.SellerSendPart || order.Status == OrderStatus.WaitBuyerConfirm ||
               order.Status == OrderStatus.Finished)
            {
                model.Shippings = OrderService.GetOrderShippings(param);
            }
            ViewBag.Sidebar = false;
            return View(model);
        }
        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Memo(string param)
        {
            var identity = User.Identity.Identity();
            var model = OrderService.GetOrderMemo(param, identity.Id, true);
            return PartialView(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="flag">Flag</param>
        /// <param name="memo">备忘</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Memo(string param, byte? flag, string memo)
        {
            var result = new SkResult<string>();
            if (memo.Length > 100)
            {
                result.Message = "备忘不能超过100个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = OrderService.UpdateOrderMemo(param, identity.Id, true, flag, memo);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "备忘失败！";
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 修改收货地址
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Address(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Address();

            var order = OrderService.GetOrder(param, identity.Id, false, true);
            if (order.ShippingType != ShippingType.Virtual)
            {
                var areas = GetAreas();
                var areaId = order.AreaId;
                var p = areaId.Substring(0, 2);
                var c = areaId.Substring(0, 4);
                //bug mvc DropDownList name不能为 province
                model.Province = new SelectList(areas.Where(o => o.Type == 1 && o.ParentId == "0"), "Id", "Name", p);
                model.City = new SelectList(areas.Where(o => o.Type == 2 && o.ParentId == p), "Id", "Name", c);
                model.District = new SelectList(areas.Where(o => o.Type == 3 && o.ParentId == c), "Id", "Name", areaId);

            }
            model.Order = order;
            ViewBag.Sidebar = false;
            return PartialView(model);
        }

        /// <summary>
        /// 修改订单地址
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="receiver">收货地址</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Address(string param, UserAddress receiver)
        {
            var result = new SkResult<string>();
            var identity = User.Identity.Identity();
            if (Request.IsAuthenticated)
            {
                var order = OrderService.GetOrder(param, identity.Id, false, true);
                if (order.Status != OrderStatus.WaitSellerSend)
                {
                    result.Message = "当前订单状态不可修改收货信息！";
                }
                else
                {
                    if (receiver.Name.IsNullOrEmpty())
                    {
                        result.Message = "请填写收货人的姓名！";
                        return Json(result);
                    }
                    if (receiver.Address.IsNullOrEmpty())
                    {
                        result.Message = "请填写收货人的详细地址！";
                        return Json(result);
                    }
                    if (receiver.Mobile.IsNullOrEmpty() || receiver.Phone.IsNullOrEmpty())
                    {
                        result.Message = "电话和手机请至少填写一个！";
                        return Json(result);
                    }
                    if (!receiver.Phone.IsNullOrEmpty() && !receiver.Phone.IsPhone())
                    {
                        result.Message = "请填写正确的电话号码！";
                        return Json(result);
                    }
                    if (!receiver.Mobile.IsNullOrEmpty() && !receiver.Mobile.IsMobile())
                    {
                        result.Message = "请填写正确的手机号码！";
                        return Json(result);
                    }
                    if (!receiver.PostalCode.IsPostalCode())
                    {
                        result.Message = "请填写正确的邮政编码！";
                        return Json(result);
                    }
                    var areas = GetAreaNames(receiver.AreaId, GetAreas());
                    receiver.Province = areas.Item1;
                    receiver.City = areas.Item2;
                    receiver.District = areas.Item3;
                    var status = OrderService.UpdateOrderAddress(param, identity.Id, true, receiver);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "修改收货信息失败！";
                    }
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Cancel(string param)
        {
            var identity = User.Identity.Identity();
            var model = new SkResult<Order>();
            if (Request.IsAuthenticated)
            {
                var order = OrderService.GetOrderStatus(param, identity.Id, true);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                    else
                    {
                        model.Message = "该订单当前状态不可关闭交易！";
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="reason">取消原因</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cancel(string param, string reason)
        {
            var result = new SkResult<Order>();
            var identity = User.Identity.Identity();
            var order = OrderService.GetOrderStatus(param, identity.Id, true);
            if (order == null)
            {
                result.Message = "订单不存在！";
                return Json(result);
            }
            if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
            {
                var status = OrderService.UpdateOrderStatus(param, identity.Id, true, OrderStatus.Canceled, order.Version, reason);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "取消订单失败！";
                }
            }
            else
            {
                result.Message = "该订单当前状态不可取消！";
            }
            return Json(result);
        }

        /// <summary>
        /// 延长收货时间
        /// </summary>
        /// <returns></returns>
        public ActionResult Delay(string param)
        {
            var identity = User.Identity.Identity();
            var model = new SkResult<Order>();
            if (Request.IsAuthenticated)
            {
                var order = OrderService.GetOrderStatus(param, identity.Id, true);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status != OrderStatus.WaitBuyerConfirm)
                    {
                        model.Message = "该订单当前状态不可延长收货时间！";
                    }
                    else
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 延长收货时间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delay(string param, int day)
        {
            var result = new SkResult<string>();
            var identity = User.Identity.Identity();
            if (Request.IsAuthenticated)
            {
                if (day.In(new[] { 3, 5, 7, 10 }))
                {
                    var order = OrderService.GetOrderStatus(param, identity.Id, true);
                    if (order == null)
                    {
                        result.Message = "订单不存在！";
                        return Json(result);
                    }
                    if (order.Status == OrderStatus.WaitBuyerConfirm)
                    {
                        var status = OrderService.UpdateOrderExpiration(param, identity.Id, day, order.Version);
                        if (status)
                        {
                            result.Status = true;
                        }
                        else
                        {
                            result.Message = "取消订单失败！";
                        }
                    }
                    else
                    {
                        result.Message = "该订单当前状态不可延长收货时间！";
                    }
                }
                else
                {
                    result.Message = "参数不正确！";
                }
            }
            else
            {
                result.Message = "登录超时请重新登录！";
            }
            return Json(result);
        }

        public ActionResult Edit(string param)
        {
            return PartialView();
        }
    }
}
